<?php

class Tools extends CApplicationComponent{
	
	public function init(){
		
	}

	public function modelsToArray($models,$attribute=array(),$keyField = null){
	    $array = array();
	    if (is_array($models)){
	        foreach ($models as $model){
	            if (!empty($attribute)){
	                $attributes = array_intersect_key($model->attributes,array_flip($attribute));
	            }else{
	                $attributes = $model->attributes;
	            }
	            if ($keyField !== null){
	                $array[$model->$keyField] = $attributes;
	            }else{
	                $array[] = $attributes;
	            }
	        }
	    }else{
	        if (!empty($attribute)){
	            $attributes = array_intersect_key($model->attributes,array_flip($attribute));
	        }else{
	            $attributes = $model->attributes;
	        }
	        $array = $attributes;
	    }
	    
	    return $array;
	}
	
	public function getIp() {
		$onlineip = '';
		if(isset($_SERVER['HTTP_CLIENT_IP'])){
			$onlineip = $_SERVER['HTTP_CLIENT_IP'];
		}elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
			$onlineip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		}else{
			$onlineip = $_SERVER['REMOTE_ADDR'];
		}
		return $onlineip;
	}
	
	public function getSessionIds($sessionkey){
		if(empty(Yii::app()->session[$sessionkey])){
			$ids = array();
		}else{
			$ids = Yii::app()->session[$sessionkey];
		}
		return $ids;
	}
	
	public function setSessionIds($sessionkey,$oldids,$addid){
		array_push($oldids, $addid);
		$ids = array_filter($oldids);
		Yii::app()->session[$sessionkey] = $ids;
		return $ids;
	}
	
	public function state($stateValue){
		$stateData = State::model()->find(' id = :value',array(':value' => $stateValue));
		return $stateData;
	}
	
	public function country($countryValue){
		$countryData = Country::model()->find(' id = :value',array(':value' => $countryValue));
		return $countryData;
	}
	
	public function serverEnvironment($url){
		$newurl = $url;
		if(Yii::app()->params['server_environment']=='live'){
			if(strstr($url,'http')){
				$newurl = str_replace('http', 'https', $url);
			}else{
				$newurl = 'https:/'.$url;
			}
		}else{
			if(strstr('http', $url)){
				$newurl =  $url;
			}else{
				$newurl = 'http:/'.$url;
			}
		}
		return $newurl;
	}
	
	public function formatDate($format,$time,$difftime=''){
		if(!empty($time)){
			return date($format,$time+$difftime);
		}else{
			return '';
		}
	}
}